// --------------------------------------------------------------------------------------------------------------------
// <copyright file="FeedUserControl.cs" company="Tobias Lekman">
//   Licensed under Microsoft Public License (Ms-PL). See lekman.codeplex.com/license for more information.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace LekmanCom.Controls
{
    using System;
    using System.IO;
    using System.Net;
    using System.Text;
    using System.Web.UI;
    using System.Xml.Linq;

    /// <summary>
    /// Base class for user controls that render data from feeds.
    /// </summary>
    public abstract class FeedUserControl : UserControl
    {
        #region Constants and Fields

        /// <summary>
        /// The URL of the web feed.
        /// </summary>
        private readonly string _feedUrl;

        /// <summary>
        /// Static backup for rendering updates should the feed be offline.
        /// </summary>
        private static string _lastMessage;

        #endregion

        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="FeedUserControl"/> class.
        /// </summary>
        /// <param name="feedUrl">
        /// The feed URL.
        /// </param>
        protected FeedUserControl(string feedUrl)
        {
            this._feedUrl = feedUrl;
        }

        #endregion

        #region Methods

        /// <summary>
        /// Gets the feed as XML.
        /// </summary>
        /// <param name="url">
        /// The feed URL.
        /// </param>
        /// <returns>
        /// The tweet updates as an <see cref="XElement"/> structure.
        /// </returns>
        protected static XElement GetXmlFeed(string url)
        {
            string data = null;
            try
            {
                 HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
                using (HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse())
                {
                    using (Stream stream = response.GetResponseStream())
                    {
                        if (stream != null)
                        {
                            StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                            data = reader.ReadToEnd();
                        }
                    }
                }

                if (data != null)
                {
                    _lastMessage = data;
                }
            }
            catch (Exception)
            {
                data = _lastMessage;
            }

            return string.IsNullOrEmpty(data) ? null : XElement.Parse(data);
        }

        /// <summary>
        /// Called when the XML data binds.
        /// </summary>
        /// <param name="data">
        /// The XML data.
        /// </param>
        protected abstract void OnDataBind(XElement data);

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">
        /// The source of the event.
        /// </param>
        /// <param name="e">
        /// The <see cref="System.EventArgs"/> instance containing the event data.
        /// </param>
        protected void Page_Load(object sender, EventArgs e)
        {
            this.BindData();
        }

        /// <summary>
        /// Gets the feed data and binds it to the control.
        /// </summary>
        private void BindData()
        {
            XElement data = GetXmlFeed(this._feedUrl);

            if (data == null)
            {
                this.Visible = false;
                return;
            }

            this.OnDataBind(data);
        }

        #endregion
    }
}